import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributeView;
import java.nio.file.attribute.BasicFileAttributes;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Pattern;

public class GenMavenDeployBat {
    /**
     * Durl 是 Nexus 仓库地址
     * DrepositoryId 是仓库名称
     * DgeneratePom 是否生成 jar 包的 POM
     */
    public static final String BASE_CMD = "mvn " +
            "-s D:\\maven363\\conf\\settings.xml " +
            "deploy:deploy-file " +
            "-Durl=http://localhost:8081/repository/thirdparty/ " +
            "-DrepositoryId=thirdparty " +
            "-DgeneratePom=true";

    public static final Pattern DATE_PATTERN = Pattern.compile("-[\\d]{8}\\.[\\d]{6}-");

    /**
     * 第1个参数是上次 jar 的路径，第2个参数是 jar 包生成的地址
     *
     * @param args
     */
    public static void main(String[] args) {
        Date modDt = null;
        String jarPath = null;
        try {
            if (args.length >= 1) {
                jarPath = args[0];
            }
            if (args.length >= 2) {
                modDt = new SimpleDateFormat("yyyy-MM-dd#HH:mm:ss").parse(args[1]);
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        deploy(new File(jarPath).listFiles(), modDt);
    }

    public static void deploy(File[] files, Date modDt) {
        if (files.length == 0) {
            //ignore
        } else if (files[0].isDirectory()) {
            for (File file : files) {
                if (file.isDirectory()) {
                    deploy(file.listFiles(), modDt);
                }
            }
        } else if (files[0].isFile()) {
            File pom = null;
            File jar = null;
            File source = null;
            File javadoc = null;
            //忽略日期快照版本，如 xxx-mySql-2.2.6-20170714.095105-1.jar
            boolean ignore = false;
            for (File file : files) {
                String name = file.getName();
                if (DATE_PATTERN.matcher(name).find()) {
                    //skip
                } else if (name.endsWith(".pom")) {
                    pom = file;
                } else if (name.endsWith("-javadoc.jar")) {
                    javadoc = file;
                } else if (name.endsWith("-sources.jar")) {
                    source = file;
                } else if (name.endsWith(".jar")) {
                    jar = file;
                }
            }

            if (pom != null) {
                if (jar != null) {
                    if (modDt != null && readCreateTime(pom) > modDt.getTime()) {
                        ignore = true;
                    }
                    if (ignore) {
                        deploy(pom, jar, source, javadoc);
                    }
                } else if (packingIsPom(pom)) {
                    if (modDt != null && readCreateTime(pom) > modDt.getTime()) {
                        ignore = true;
                    }
                    if (ignore) {
                        deployPom(pom);
                    }
                }
            }
        }
    }

    public static boolean packingIsPom(File pom) {
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new InputStreamReader(new FileInputStream(pom)));
            String line;
            while ((line = reader.readLine()) != null) {
                if (line.trim().indexOf("<packaging>pom</packaging>") != -1) {
                    return true;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                reader.close();
            } catch (Exception e) {
            }
        }
        return false;
    }

    public static String deploy(final File pom, final File jar, final File source, final File javadoc) {
        StringBuffer cmd = new StringBuffer(BASE_CMD);
        cmd.append(" -DpomFile=").append(pom.getAbsolutePath());
        if (jar != null) {
            //当有bundle类型时，下面的配置可以保证上传的jar包后缀为.jar
            cmd.append(" -Dpackaging=jar -Dfile=").append(jar.getAbsolutePath());
        } else {
            cmd.append(" -Dfile=").append(pom.getAbsolutePath());
        }
        if (source != null) {
            cmd.append(" -Dsources=").append(source.getName());
        }
        if (javadoc != null) {
            cmd.append(" -Djavadoc=").append(javadoc.getName());
        }
        System.out.println(cmd.toString());
        return cmd.toString();
    }

    public static String deployPom(final File pom) {
        String cmd = BASE_CMD;
        cmd += " -DpomFile=" + pom.getAbsolutePath();
        cmd += " -Dfile=" + pom.getAbsolutePath();
        System.out.println(cmd);
        return cmd;
    }

    public static long readCreateTime(File file) {
        try {
            Path path = Paths.get(file.getAbsolutePath());
            BasicFileAttributeView basicview = Files.getFileAttributeView(path, BasicFileAttributeView.class, LinkOption.NOFOLLOW_LINKS);
            BasicFileAttributes attr = basicview.readAttributes();
            return attr.creationTime().toMillis();
        } catch (Exception e) {
            e.printStackTrace();
            return file.lastModified();
        }
    }
}
